package pers.ht.mbpo.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DaoUtil {

    //禁止外部实例化
    private DaoUtil() {
    }

    //增删改方法的抽象
    public static void update(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject(i + 1, args[i]);
                }
            }
            ps.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close(null, ps, conn);
        }
    }

    //校验代码方法
    public static Boolean checkId(String tableName, String pk, String value) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "SELECT " + pk + " FROM " + tableName + " WHERE " + pk + " = ?";
        String s = "";
        boolean flag = true;
        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setObject(1, value);
            rs = ps.executeQuery();
            while (rs.next()) {
                s = rs.getString(1);
            }
            DBUtil.close(rs, ps, conn);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        if (value.equals(s)) {
            flag = false;
        }
        return flag;
    }
}
